package com.sky.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;

@Slf4j
@Data
@AllArgsConstructor
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    // 上传文件方法
    public String upload(byte[] bytes, String objectName) {
        // 创建 OSS 客户端实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            log.info("开始上传文件，文件名: {}, 文件大小: {} bytes", objectName, bytes.length);

            // 上传文件到 OSS
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));

            // 拼接文件 URL
            String fileUrl = String.format("https://%s.%s/%s", bucketName, endpoint.replace("http://", "").replace("https://", ""), objectName);
            log.info("文件上传成功，文件 URL: {}", fileUrl);

            return fileUrl;
        } catch (ClientException e) {
            log.error("OSS 客户端异常: {}", e.getMessage());
            throw new RuntimeException("客户端错误", e);
        } catch (Exception e) {
            log.error("文件上传失败: {}", e.getMessage());
            throw new RuntimeException("上传失败", e);
        } finally {
            // 关闭 OSS 客户端
            ossClient.shutdown();
        }
    }
}
